package com.lnsoft.cac.server.handle.codec.frameMessage;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.NonNull;

@Data
/**
 * 配置/状态交互---装置所属CAC信息查询/设置
 * */
public class Cfg_CACSub_Msg {
    private int Request_Set_Flag;       //1byte         参数配置类型标识：①0x00查询CAC地址信息②0x01设置CAC地址信息
    private int Request_Flag;           //1byte         标识位：标识选择请求或设置的参数，字节位自低向高依次对应9-11的各选择请求或设置的参数项。
    private int CAC_IP;                 //4byte         CAC IP地址
    private int CAC_PORT;               //2byte         CAC :端口号
    private byte[] Call_Centor;         //20byte        CAC电话号码（字符串）


    public ByteBuf toByteBuf() throws Exception{
        if (Request_Set_Flag != (byte)0x00 && Request_Set_Flag != (byte)0x01) {
            throw new Exception("参数配置类型标识设置异常");
        }
        if (Call_Centor == null) {
            Call_Centor = new byte[20];
        }
        if (Call_Centor.length != 20) {
            throw new Exception("CAC电话号码设置异常");
        }

        ByteBuf bf = Unpooled.buffer(28);
        bf.writeByte(Request_Set_Flag);
        bf.writeByte(Request_Flag);
        bf.writeInt(CAC_IP);
        bf.writeShort(CAC_PORT);
        bf.writeBytes(Call_Centor);
        return bf;
    }



    //  解析 { 配置/状态交互---装置所属CAC信息查询/设置 } 帧报文内容区 到消息体中
    public static Cfg_CACSub_Msg decFrameBody(@NonNull byte[] frameBody) throws Exception {
        ByteBuf bf = Unpooled.wrappedBuffer(frameBody);
        Cfg_CACSub_Msg msg = new Cfg_CACSub_Msg();
        int len = frameBody.length;
        if (len == 0) {
            return null;
        }
        if (len != 28) {
            throw new Exception("frameBody 数据异常");
        }
        msg.setRequest_Set_Flag(bf.getByte(0) & 0xFF);
        msg.setRequest_Flag(bf.getByte(1) & 0xFF);
        msg.setCAC_IP(bf.getInt(2) & 0xFFFFFFFF);
        msg.setCAC_PORT(bf.getShort(6) & 0xFFFF);
        byte[] Call_Centor = new byte[20];
        bf.getBytes(8, Call_Centor, 0, 20);
        msg.setCall_Centor(Call_Centor);
        return msg;
    }

}
